import { _decorator, AudioClip, AudioSource, Component, director, find, instantiate, Node, Prefab } from 'cc';
import ResManager from './ResManager';
import { PrefabEnum } from './PrefabEnum';
const { ccclass, property } = _decorator;

export enum Mp3Enum{
    /**世界地图背景音乐 */
    world_0 = 'mp3/world_0',
    /**内城背景音乐 */
    innercity_0 = 'mp3/innercity_0',
    /**鼠标点击 */
    mouse_click = 'mp3/mouse_click',
    /**按钮确认 */
    btn_confirm = 'mp3/btn_confirm',
    /**建造中 */
    construction_building = 'mp3/construction_building',
    /**建造完成 */
    construction_complete = 'mp3/construction_complete',
    /**拆除 */
    construction_downgrade = 'mp3/construction_downgrade',
    /**英雄升星 */
    hero_addstar = 'mp3/hero_addstar',
    /**英雄升级 */
    hero_lvlup = 'mp3/hero_lvlup',
    /**收到邮件 */
    notification_mail = 'mp3/notification_mail',
    /**研究完成 */
    research_complete = 'mp3/research_complete',
}

@ccclass('AudioManager')
export class AudioManager  {
    private static _instance: AudioManager;

    static get instance(): AudioManager {
        if (this._instance == null) {
            this._instance = new AudioManager();
        }

        return this._instance
    }

    private _audioSource: AudioSource;

    timeMap:Map<string, number> = new Map()

    constructor() {
        //@en create a node as audioMgr
        //@zh 创建一个节点作为 audioMgr
        let audioMgr = new Node();
        audioMgr.name = '__audioMgr__';

        //@en add to the scene.
        //@zh 添加节点到场景
        director.getScene().addChild(audioMgr);

        //@en make it as a persistent node, so it won't be destroied when scene change.
        //@zh 标记为常驻节点，这样场景切换的时候就不会被销毁了
        director.addPersistRootNode(audioMgr);

        //@en add AudioSource componrnt to play audios.
        //@zh 添加 AudioSource 组件，用于播放音频。
        this._audioSource = audioMgr.addComponent(AudioSource);
    }

    async playClip(path:string){
        let assert = await ResManager.instance.loadAssetByUrl<AudioClip>(path)
        this._audioSource.stop();
        this._audioSource.loop = true
        this._audioSource.clip = assert;
        this._audioSource.play();
    }

    async playOneShot(path:string){
        if(this.timeMap.has(path)){
            let time = this.timeMap.get(path)
            let now = new Date().getTime()
            if(now - time < 500){
                return
            }
        }

        this.timeMap.set(path, new Date().getTime())
        let assert = await ResManager.instance.loadAssetByUrl<AudioClip>(path)
        this._audioSource.playOneShot(assert);
    }

    /**
     * stop the audio play
     */
    stop() {
        this._audioSource.stop();
    }

    /**
     * pause the audio play
     */
    pause() {
        this._audioSource.pause();
    }

    /**
     * resume the audio play
     */
    resume(){
        this._audioSource.play();
    }
}


